<%@ page language="java" pageEncoding="UTF-8"%>
<%@ include file="/mb/jsp/common.jsp" %>
<!doctype html>
<html>
<head>
    <title>html 5 minutes chart painter</title>
    <script src="mb/libs/loading.js" type="text/javascript"></script>
    <script src="mb/libs/util.js" type="text/javascript"></script>
    <script src="mb/libs/absPainter.js" type="text/javascript"></script>
    <script src="mb/libs/ajax.js" type="text/javascript"></script>
    <script src="mb/libs/crossLines.js" type="text/javascript"></script>
    <script src="mb/libs/axis-x.js" type="text/javascript"></script>
    <script src="mb/libs/linepainter.js" type="text/javascript"></script>
    <script src="mb/libs/volumePainter.js" type="text/javascript"></script>
    <script src="mb/libs/axis-y.js" type="text/javascript"></script>
    
    <script src="mb/libs/chartEventHelper.js?a" type="text/javascript"></script>
    <!--  <script src="libs/mins-data.js"></script>  -->  
</head>
<body>
    <canvas id="canvas" style="z-index: 3;  background: white; border: 1px solid #69c">
        <p> 你的浏览器不支持html5哟</p>
    </canvas>
    <!--
    options:{
        fallColor:'green',riseColor:'red',normalColor:'black',
        topText:{font:'11px 宋体',color:'black',region:{x:.5,y:.5,width:213,height:20}},
        minsChart:{region:{x:2,y:20,width:180,height:150},priceLineColor:'blue',middleLineColor:'red',otherSplitLineColor:'lightgray',borderColor:'gray'},
        xScaler:{font:'11px 宋体',color:black,region:{x:5,y:130,width:180,height:20}},
        bottomText:{font:'11px 宋体',color:'black',region:{x:5,y:130,width:213,height:20}}
    }
    -->
  
<script type="text/javascript">
    
    var MinsKdata;
    var endDataDtime_Mins=0;//
    var aboutV=0;
    $().ready(function() { 
       
        var heightAuto = $(window).height();
        var widthAuto = $(window).width();
        console.log(widthAuto);
        $('#canvas').attr('width',widthAuto);

        	
    	MinsKdata = getQuote();
        chart.paint(MinsKdata);
	    loadBuyUserList2();
	    setInterval(loadBuyUserList2,5000);
  	});
   	
  	function getQuote() {
            return {
                quote: {
                    vrgoodsid:0,
                    time: 0,
                    open: 0,
                    preClose: 0,
                    highest: 0,
                    lowest: 0,
                    price: 0,
                    nowPri:0,
                    volume: 0,
                    amount: 0
                },
                buysell:{},
                timeid:0,
                isinit:true,
                mins: []
            }
    }
  	 
  	//取支持数据 k线类型
	function loadBuyUserList2()
	{

	    //var projectidV=$("#P_projectid").html();
		$.ajax({
	            url: "LoginServlet",
	            //data: JSON.stringify({m:281,type:KType,endtime:endDataDtime_Mins}),
	            data: JSON.stringify({m:283,timeid:endDataDtime_Mins,about:aboutV}),
	            type: 'post',
	            dataType: 'json',
	            contentType:"application/json;charset=utf-8",
	            success: function (data) {
	            	console.log(data);
	   	            if(data['state']==1)
		            {
		                endDataDtime_Mins=data.obj.timeid*1;
		                endDataDtime=data.obj.timeid*1;
		                if(endDataDtime==0)
		                {
		                	Kdata=data.obj;
			                Kdata.isinit=true;
			                chart.paint(Kdata);
		                }
		                if(data.obj!=null && data.obj.mins!=null && data.obj.mins.length>0){
		                  	if(MinsKdata.isinit) //初始状态
			                {
			                    
			                    MinsKdata=data.obj;
			                	MinsKdata.isinit=false;
			                	chart.paint(MinsKdata);
			                }
			                else //追加数据
			                {
			                	MinsKdata.isinit=false;
			                	MinsKdata.quote=data.obj.quote;
			                	MinsKdata.buysell=data.obj.buysell;
			                	
			                	MinsKdata.timeid=data.obj.timeid;
			                	
			                	var lenK=MinsKdata.mins.length;
			                	var lenO=data.obj.mins.length;
			                	if(lenK<=lenO)
			                	{
			                		MinsKdata.mins=data.obj.mins;
			                	}
			                	else
			                	{ 
			                	   	 for(var tm=lenK;tm>0;tm--)
			                		 {
			                		   	if(MinsKdata.mins[tm-1].timeid*1.0==data.obj.mins[0].timeid*1.0)
			                		   	{
			                		   		var dd=MinsKdata.mins.splice(tm-1,lenK-tm+1);
			                		   		break;
				                		}
			                		 }
			                	    $.each(data.obj.mins, function(index, objVal) 
			                		{
			                			MinsKdata.mins.push(objVal);
			                		});
			                	}
			                	chart.paint(MinsKdata);
			                }
			                $("#nowprice", parent.document).html(data.obj.quote.price);
		                
		                }
		           }
		           else
		           {
		           
		           }
		        },
		        error: function (data) {
                 	return false;
                },
         });
    }  
    
    
    
    
    
    
    
        function line(ctx, x0, y0, x1, y1, color, width) {
            ctx.beginPath();
            ctx.moveTo(x0, y0);
            ctx.lineTo(x1, y1);
            ctx.strokeStyle = color;
            ctx.lineWidth = width || 1;
            ctx.stroke();
        }

        function getMinTime(minIndex) {
            //上午09：30-11：30
            //下午13：00-15：00
/*             var d = new Date();
            if (minIndex <= 120) { //120 上午的9:30-11:30   
                d.setHours(9, 30, 30);
                d = new Date(d.getTime() + (minIndex) * 60 * 1000);
            } else {
                d.setHours(13, 0, 0);
                d = new Date(d.getTime() + (minIndex - 120) * 60 * 1000);
            } 
            
*/

			var d = new Date();
			d.setHours(9, 00, 30);  //9:00开盘
			d = new Date(d.getTime() + (minIndex) * 60 * 1000);
			
            var hour = d.getHours() > 9 ? new String(d.getHours()) : '0' + d.getHours();
            var minutes = d.getMinutes() > 9 ? new String(d.getMinutes()) : '0' + d.getMinutes();
            var seconds = '30';
            return hour + '' + minutes + seconds;
        }

        function Tip(options) {
            this.options = options;
            this.canvas = options.canvas;
            this.canvas.tip = this;
        }

        Tip.prototype = {
            show: function (relativePoint, html) {
                var dc = this.dataContext;
                var painter = this.canvas.painter;
                if (dc) {
                    if (dc.isNewQuote) painter.fillTopText(dc.data);
                    else painter.fillTopText(dc.data, dc.index);
                }
            },
            update: function (relativePoint, html) { 
                this.show(relativePoint, html);
            },
            hide: function () {
                var dc = this.dataContext;
                var painter = this.canvas.painter;
                if (dc) {
                    painter.fillTopText(dc.data);
                }
            }
        };

        function minsChart(canvasId, options) {
            extendObject(options, this);
            this.canvas = $id(canvasId);
            this.ctx = this.canvas.getContext('2d');
            this.canvas.painter = this;
        }

        minsChart.prototype = {
            /*
            data format like :{
            quote: {
            time: 20111214150106,
            open: 2241.390,
            preClose: 2248.590,
            highest: 2256.740,
            lowest: 2224.730,
            price: 2228.530,
            volume: 4407982200,
            amount: 38621178573
            },
            mins: [
            {price:2239.45,volume:49499299,amount:459279327}
            ]
            }
            */
            paint: function (data) {
            
                var canvas = this.canvas;
                var ctx = this.ctx;
                this.painting = true;
                var options = this.klOptions;
                var clearPart = { width: canvas.width, height: canvas.height };
                
                ctx.clearRect(0, 0, clearPart.width, clearPart.height);
									
                ctx.save();
                
                this.fillTopText(data);
                this.paintChart(data);
                this.paintxAxis();
                this.fillBottomText(data);
                this.paintVolume(data);
            },

            paintVolume: function (data) {
                var ctx = this.ctx;
                var options = this.volume;
                ctx.beginPath();
                ctx.rect(options.region.x, options.region.y, options.region.width, options.region.height);
                ctx.strokeStyle = options.borderColor;
                ctx.stroke();
                line(ctx, options.region.x, options.region.y + options.region.height / 2, options.region.x + options.region.width, options.region.y + options.region.height / 2, options.splitLineColor);
                options.getDataLength = function () { return this.data.items.length; };
                options.maxDotsCount = this.maxDotsCount;
                var volumePainterImp = new volumePainter(options);
                var painter = new Painter(this.canvas.id, volumePainterImp, { items: data.mins });
                painter.paint();

                var max = painter.maxVolume;
                var unit;
                if (max / 1000000 > 1000) {
                    max = max / 1000000;
                    unit = '百万';
                } else if(max / 10000 > 1000){
                    max = max / 10000;
                    unit = '万';
                }
                else
                {
                    max = max / 100;
                    unit = '百';
                }
                var scalers = [max.toFixed(2), (max / 2).toFixed(2), '(' + unit + ')'];
                var yscaler = new yAxis(this.volume.yScaler);
                var painter = new Painter(this.canvas.id, yscaler, scalers);
                painter.paint();
            },

            fillBottomText: function (data) {
                if (!this.bottomText) return;
                //高9999 低9999 成交888999
                var ctx = this.ctx;
                var txt = '高';
                var options = this.bottomText;
                ctx.font = options.font;
                ctx.fillStyle = options.color;
                var w = ctx.measureText(txt).width;
                ctx.fillText(txt, options.region.x, options.region.y);
                var x = options.region.x + w;
                var quote = data.quote;
                var me = this;
                function getTxtColor(val) { return val > quote.preClose ? me.riseColor : (val == quote.preClose ? me.normalColor : me.fallColor); }
                var highColor = getTxtColor(quote.highest);
                var high = toMoney(quote.highest);
                ctx.fillStyle = highColor;
                w = ctx.measureText(high).width;
                ctx.fillText(high, x, options.region.y);
                x += w;
                txt = ' 低';
                ctx.fillStyle = options.color;
                w = ctx.measureText(txt).width;
                ctx.fillText(txt, x, options.region.y);
                x += w;
                var lowColor = getTxtColor(quote.lowest);
                var low = toMoney(quote.lowest);
                w = ctx.measureText(low).width;
                ctx.fillStyle = lowColor;
                ctx.fillText(low, x, options.region.y);
                x += w;
                ctx.fillStyle = options.color;
                var amount = ' 成交' + bigNumberToText(quote.amount);
                ctx.fillText(amount, x, options.region.y);
            },

            paintxAxis: function () {
                var xAxisImpl = new xAxis(this.xScaler);
                var xAxisPainter = new Painter(this.canvas.id, xAxisImpl, this.xScaler.data);
                xAxisPainter.paint();
            },

            paintChart: function (data) {
                var minsChartOptions = this.minsChart;
                var region = this.minsChart.region;
                var ctx = this.ctx;
                ctx.beginPath();
                ctx.strokeStyle = minsChartOptions.borderColor;
                ctx.rect(region.x, region.y, region.width, region.height);
                ctx.stroke();
                
                //水平线
                var middleIndex = (this.minsChart.horizontalLineCount + this.minsChart.horizontalLineCount % 2) / 2;
                
                var splitCount = this.minsChart.horizontalLineCount + 1;
                for (var i = 1; i <= this.minsChart.horizontalLineCount; i++) {
                    var color = (i == middleIndex ? minsChartOptions.middleLineColor : minsChartOptions.otherSplitLineColor);
                    var y = region.y + region.height * i / splitCount;
                    line(ctx, region.x, y, region.x + region.width, y, color);
                }
                //垂直线 
                splitCount = this.minsChart.verticalLineCount + 1;
                for (var i = 1; i <= this.minsChart.verticalLineCount; i++) {
                    var x = region.x + region.width * i / splitCount;
                    line(ctx, x, region.y, x, region.y + region.height, minsChartOptions.otherSplitLineColor);
                }

                //价格线
                var lineOptions = {
                    region: region,
                    maxDotsCount: this.maxDotsCount,
                    getDataLength: function () { return this.data.items.length; },
                    getItemValue: function (item) { return item.price; },
                    middleValue: data.quote.preClose, //通常是昨收
                    lineColor: minsChartOptions.priceLineColor
                };
                var linePainterImp = new linePainter(lineOptions);
                var priceLinePainter = new Painter(this.canvas.id, linePainterImp, { items: data.mins });
                priceLinePainter.paint();

                //y轴
                var yOptions = this.minsChart.yScalerLeft;
                var preClose = data.quote.preClose;
                var me = this;
                yOptions.color = function (val) {
                    return val > preClose ? me.riseColor : (val == preClose ? me.normalColor : me.fallColor);
                };
                var scalersLeft = [];
                var scalersRight = [];
                var min = preClose - priceLinePainter.maxDiff;
                var space = priceLinePainter.maxDiff * 2 / (this.minsChart.horizontalLineCount + 1);
                for (var i = this.minsChart.horizontalLineCount + 1; i >= 0; i--) {
                    var val = min + i * space;
                    scalersLeft.push(val.toFixed(2));
                    if(preClose!=0){var percent = (val - preClose) * 100 / preClose; }
                    else{var percent = 0;}
                    scalersRight.push(percent.toFixed(2) + '%');
                }
                var yx = new yAxis(yOptions);
                var yAxisPainter = new Painter(this.canvas.id, yx, scalersLeft);
                yAxisPainter.paint();

                var yPercentOptions = this.minsChart.yScalerRight;
                yPercentOptions.color = function (val) {
                    return (val == '0.00%' ? 'black' : (val.charAt(0) == '-' ? 'green' : 'red'));
                };
                var yxPercent = new yAxis(yPercentOptions);
                var yxPercentPainter = new Painter(this.canvas.id, yxPercent, scalersRight);
                yxPercentPainter.paint();


                //均线
                if (this.needPaintAvgPriceLine) {
                    //生成移动均线数据
                    var items = [];
                    var totalVolume = 0;
                    var totalAmount = 0;
                    data.mins.each(function (item) {
                       totalVolume += item.volume*1.0;
                        totalAmount += item.amount*1.0;
                        
                        if(totalVolume*1.0==0)
                        {   
                        	items.push(item.price*1.0);
                        }
                        else
                        	items.push(totalAmount / totalVolume);
                    });
                    lineOptions.lineColor = minsChartOptions.avgPriceLineColor;
                    lineOptions.getItemValue = function (item) { return item; };
                    linePainterImp = new linePainter(lineOptions);
                    var painterAvg = new Painter(this.canvas.id, linePainterImp, { items: items });
                    painterAvg.paint();
                }

                var me = this;
                var chartRegion = me.minsChart.region;

                function getY(x) {
                    var index = Math.ceil((x - me.minsChart.region.x) * me.maxDotsCount / me.minsChart.region.width);
                    var val;
                    var isNewQuote;
                    if (index >= 0 && index < data.mins.length) {
                        val = data.mins[index].price;
                        isNewQuote = false;
                    } else {
                        val = data.quote.price;
                        isNewQuote = true;
                    }

                    if (me.canvas.tip) me.canvas.tip.dataContext = { data: data, isNewQuote: isNewQuote, index: index };
                    var diff = val - preClose;
                    var middleY = (me.minsChart.region.y + me.minsChart.region.height / 2);
                    return middleY - diff * me.minsChart.region.height / 2 / priceLinePainter.maxDiff;
                }

                //添加鼠标事件
                addCrossLinesAndTipEvents(this.canvas, {
                    getCrossPoint: function (ev) { return { x: ev.offsetX, y: getY(ev.offsetX) }; },
                    triggerEventRanges: { x: chartRegion.x, y: chartRegion.y, width: chartRegion.width, height: me.volume.region.y + me.volume.region.height - chartRegion.y },
                    tipOptions: {
                        getTipHtml: function (ev) { return null; },
                        position: { x: false, y: false }
                    },
                    crossLineOptions: {
                        color: 'black'
                    }
                });
            },

            fillTopText: function (data, minIndex) {
                var quote = data.quote;
                var ctx = this.ctx;
                var topText = this.topText;
                var region = topText.region;
                ctx.clearRect(region.x, region.y, region.width, region.height);
                var price;
                var time;
                if (typeof minIndex == 'undefined') {
                    price = quote.price;
                    time = quote.time;
                } else {
                    price = data.mins[minIndex].price;
                    time = quote.time.toString().substr(0, 8) + getMinTime(minIndex);
                }
                ctx.fillStyle = topText.color;
                ctx.font = topText.font;
                if (topText.textBaseline) ctx.textBaseline = topText.textBaseline;
                var txt = '最新' + toMoney(price);
                var width = ctx.measureText(txt).width;
                ctx.fillText(txt, topText.region.x, topText.region.y);

                var isRise = price > quote.preClose;
                var isEqual = price == quote.preClose;
                var isFall = price < quote.preClose;
                var diff = toMoney(price - quote.preClose);
                var txtRiseFall = (isRise ? '↑' : (isFall ? '↓' : '')) + diff
            + ('(')
            + toMoney(diff * 100 / quote.preClose)
            + '%)';

                var x = topText.region.x + width;
                ctx.fillStyle = isRise ? this.riseColor : (isFall ? this.fallColor : this.normalColor);
                ctx.fillText(txtRiseFall, x, topText.region.y);
                var temp = new String(time);
                var txtTime = temp.charAt(8) + temp.charAt(9) + ':' + temp.charAt(10) + temp.charAt(11);
                
                ctx.fillStyle = topText.color;
                var timeWidth = ctx.measureText(txtTime).width;
                ctx.fillText(txtTime, topText.region.x + topText.region.width - timeWidth, topText.region.y);
            }
        };
        var divH=document.getElementById("canvas").getAttribute('height');
        var divW=document.getElementById("canvas").getAttribute('width');
 
        
        var divW=screen.availWidth;
        var divH=divW*0.65;
               
        document.getElementById("canvas").setAttribute("width", divW);
        document.getElementById("canvas").setAttribute("height", divH);
        
       
        var rateH=(divH)/310;  //高 放大倍数
        var rateW=(divW)/414;  //宽 放大倍数
         
        console.log("rateH="+rateH);
        console.log("rateW="+rateW);
 
        //先计算不变对的，再计算变的,即先确定能确定的
        
        //X坐标之间的间标设定
        //头部 间隔 
        var X_L1ForTop=2;  var X_R2ForTop=5;
        //Y左轴
        var X_L1ForYs=0.5;   var X_L2ForYs=4.5;  
        //Y右轴
        var X_R1ForYs=2;   var X_R2ForYs=5; 
        
        //Y坐标之间的间标设定
        //头部与顶，头部与中间画图区间隔,头部与Y轴左右区间隔
        var Y_TForTop=5.5;  var Y_BForTop=2;  var Y_BForTopYLR=0.5;
        //X轴坐标区域与上下两区域间隔
        var Y_TForXs=3.5;   var Y_BForXs=0.5;
        //下部画图区域与底部间隔 
        var Y_BForV=4.5;
        //下部画图区域Y轴 与中间X轴坐标区域间隔
        var Y_TForVY=3;
        
        var yScalerLeftX=X_L1ForYs; //0.5
        var yScalerLeftW=40.5;
        var minsChartRegionX=yScalerLeftX+yScalerLeftW+X_L2ForYs; //56.5  0.5+50.5+5.5=56.5
        
        //头部 起始XY不变，H不变，W变
        var topTextX=minsChartRegionX+X_L1ForTop; //58.5   56.5+2=58.5
        var yScalerRightW=42.5;
        var yScalerRightX=divW-yScalerRightW-X_R2ForYs; //368.5   414-40.5-5=368.5
        var minsChartRegionW=yScalerRightX-minsChartRegionX-X_R1ForYs; //310   368.5-56.5-2=310
        
        var xScalerRegionX=minsChartRegionX;
        var xScalerRegionW=minsChartRegionW; //310  topTextW+5;
        var topTextW=yScalerRightX-63; //
 
        var volumeyScalerX=yScalerLeftX; //0.5
        var volumeyScalerW=yScalerLeftW; //50.5
        
        var volumeRegionX=minsChartRegionX; //56.5
        var volumeRegionW=minsChartRegionW; //310
        
        var topTextY=Y_TForTop; //5.5
        var topTextH=14; //
        
        var yScalerLeftY=topTextY+topTextH+Y_BForTopYLR; //20  5.5+14+0.5=20
        var yScalerRightY=yScalerLeftY;//20
        var minsChartRegionY=topTextY+topTextH+Y_BForTop;  //21.5  5.5+14+2=21.5
        var xScalerRegionH=20;
        var minsChartRegionH=200*(divH-minsChartRegionY-Y_BForV-Y_TForXs-Y_BForXs-xScalerRegionH)/(200+60);   //200    (200 60  为原来高,为固定参数） 
        var yScalerLeftH=minsChartRegionH;
        var yScalerRightH=yScalerLeftH;
        
        var xScalerRegionY=Y_TForTop+topTextH+Y_BForTop+yScalerRightH+Y_TForXs;//225 5.5+14+2+200+3.5=225
        
        var volumeRegionY=xScalerRegionY+xScalerRegionH+Y_BForXs; //245.5  225+20+0.5=245.5
        var volumeRegionH=divH-volumeRegionY-Y_BForV;//60   310-245.5-4.5=60
        
        var volumeyScalerY=volumeRegionY-Y_TForVY;
        var volumeyScalerH=volumeRegionH;
      
        //柱的宽度
        var volumeBarW= 2*rateW;//2
        //Chart
        //注意:verticalLineCount 值 要与xScaler里面的data数量对应

        console.log("volumeRegionW="+volumeRegionW); //396  w=500   1.2倍
        console.log("volumeBarW="+volumeBarW);
        
        //var dateTime=['09:30','10:00','10:30','11:00', '11:30/13:00','13:30', '14:00','14:30', '15:00']; //X轴(即时间轴)显示刻度
        //var dateTime=['09:00','09:30','10:00','10:30','11:00', '11:30','12:00','12:30','13:00','13:30', '14:00','14:30', '15:00','15:30','16:00','16:30','17:00','17:30','18:00','18:30','19:00','19:30','20:00','20:30','21:00','21:30','22:00','22:30', '23:00']; //X轴(即时间轴)显示刻度
        var dateTime=['09:00','11:00','13:00','15:00','17:00','19:00','21:00','23:00']; //X轴(即时间轴)显示刻度
        var lineNum=dateTime.length-2; //与dateTime元素相对应的竖线
        var lineMins=120; //dateTime 每格相差的分钟数
        
        
        
        var chart = new minsChart('canvas', {
            fallColor: 'green', riseColor: 'red', normalColor: 'black', maxDotsCount: (dateTime.length-1)*lineMins+1, needPaintAvgPriceLine: true,
            backgroundColor:'white',
            topText: { font: '9px 宋体', color: 'black', region: { x: topTextX, y: topTextY, width: topTextW, height: topTextH }, textBaseline: 'top' },
            minsChart: {
                region: { x: minsChartRegionX, y: minsChartRegionY, width: minsChartRegionW, height: minsChartRegionH },
                priceLineColor: 'blue', avgPriceLineColor: 'Orange', middleLineColor: 'red', otherSplitLineColor: 'lightgray', borderColor: 'gray',
                horizontalLineCount: 7, verticalLineCount: lineNum,
                yScalerLeft: { font: '9px Arial', region: { x: yScalerLeftX, y: yScalerLeftY, width: yScalerLeftW, height: yScalerLeftH }, align: 'right', fontHeight: 9, textBaseline: 'top' },
                yScalerRight: { font: '9px Arial', region: { x: yScalerRightX, y: yScalerRightY, width: yScalerRightW, height: yScalerRightH }, align: 'right', fontHeight: 9, textBaseline: 'top' }
            },
            xScaler: {
                font: '9px Arial', color: 'black',
                region: { x: xScalerRegionX, y: xScalerRegionY, width: xScalerRegionW, xScalerRegionW: xScalerRegionH },
                data: dateTime
            },

            //bottomText: { font: '11px 宋体', color: 'black', region: { x: 5.5, y: 260, width: 400, height: 20} },
            volume: {
                region: { x: volumeRegionX, y: volumeRegionY, width: volumeRegionW, height: volumeRegionH },
                bar: { color: 'green', width: volumeBarW },
                borderColor: 'lightgray', splitLineColor: 'lightgray',
                yScaler: { font: '9px Arial', region: { x: volumeyScalerX, y: volumeyScalerY, width: volumeyScalerW, height: volumeyScalerH }, color: 'black', align: 'right', fontHeight: 12, textBaseline: 'top' }
            }
        });
        
  

    </script>

 

</body>
</html>
